package cn.lili.modules.lucene;

import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 15:37 2025/6/23
 */
@Component
public class IndexStateManager {
    private final AtomicReference<IndexState> state = new AtomicReference<>(IndexState.UNINITIALIZED);
    private final AtomicLong lastRebuildTimestamp = new AtomicLong(0);
    private final AtomicLong lastUpdateTimestamp = new AtomicLong(0);
    private final AtomicLong errorTimestamp = new AtomicLong(0);
    private String lastErrorMessage;

    public IndexState getCurrentState() {
        return state.get();
    }

    public boolean transition(IndexState expected, IndexState newState) {
        return state.compareAndSet(expected, newState);
    }

    public void forceState(IndexState newState) {
        state.set(newState);
    }

    public void recordRebuild() {
        lastRebuildTimestamp.set(System.currentTimeMillis());
    }

    public void recordUpdate() {
        lastUpdateTimestamp.set(System.currentTimeMillis());
    }

    public void recordError(String message) {
        errorTimestamp.set(System.currentTimeMillis());
        lastErrorMessage = message;
        forceState(IndexState.ERROR);
    }

    public long getLastRebuildTimestamp() {
        return lastRebuildTimestamp.get();
    }

    public Instant getLastRebuildInstant() {
        return Instant.ofEpochMilli(lastRebuildTimestamp.get());
    }

    public long getLastUpdateTimestamp() {
        return lastUpdateTimestamp.get();
    }

    public long getErrorTimestamp() {
        return errorTimestamp.get();
    }

    public String getLastErrorMessage() {
        return lastErrorMessage;
    }

    public long timeSinceLastRebuild() {
        return System.currentTimeMillis() - lastRebuildTimestamp.get();
    }

    public long timeSinceLastUpdate() {
        return System.currentTimeMillis() - lastUpdateTimestamp.get();
    }

    public long timeSinceLastError() {
        return System.currentTimeMillis() - errorTimestamp.get();
    }
}
